package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eic.common.util.ExceptionUtils;
import com.eic.framework.core.service.ServicePlusImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.domain.dao.SysDictType;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.mapper.SysDictTypeMapper;
import com.ruoyi.system.service.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;

/**
 * 字典 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysDictTypeServiceImpl extends ServicePlusImpl<SysDictTypeMapper,SysDictType> implements ISysDictTypeService
{
    @Autowired
    private SysDictTypeMapper dictTypeMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Override
    public boolean insert(SysDictType entity) {
        checkDictTypeUnique(entity.getDictType(),null);
        return super.insert(entity);
    }

    @Transactional
    @Override
    public boolean updateById(SysDictType entity) {
        checkDictTypeUnique(entity.getDictType(),entity.getDictId());
        return super.updateById(entity);
    }

    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        for (Serializable dictId : idList)
        {
            if (dictDataMapper.countDictDataByType(dictId.toString()) > 0)
            {
                throw new ServiceException(String.format("%1$s已分配,不能删除", dictId));
            }
        }
        return super.removeByIds(idList);
    }

    private void checkDictTypeUnique(String dictType,String dictId)
    {
        LambdaQueryWrapper<SysDictType> wrapper= Wrappers.<SysDictType>lambdaQuery().eq(SysDictType::getDictType,dictType);
        if(dictId!=null){
            wrapper.ne(SysDictType::getDictId,dictId);
        }
        SysDictType dict = dictTypeMapper.selectOne(wrapper);
        if(dict!=null){
            throw ExceptionUtils.utilException("字典类型值重复");
        }
    }
}
